package cc.shacocloud.mirage.restful.bind.support;

import cc.shacocloud.mirage.restful.HandleMethodArgumentResolver;
import cc.shacocloud.mirage.restful.HttpRequest;
import cc.shacocloud.mirage.restful.bind.WebDataBinderFactory;
import cc.shacocloud.mirage.restful.bind.validation.BindingResult;
import cc.shacocloud.mirage.restful.util.BindingResultUtil;
import cc.shacocloud.mirage.utils.MethodParameter;
import io.vertx.core.Future;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;

/**
 * 解析{@link BindingResult}方法参数
 */
public class BindingResultMethodArgumentResolver implements HandleMethodArgumentResolver {
    
    @Override
    public boolean supportsParameter(@NotNull MethodParameter parameter) {
        Class<?> paramType = parameter.getParameterType();
        return BindingResult.class.isAssignableFrom(paramType);
    }
    
    @Override
    public Future<Object> resolveArgument(@NotNull HttpRequest request,
                                          @NotNull MethodParameter parameter,
                                          WebDataBinderFactory binderFactory) {
        BindingResult bindingResult = BindingResultUtil.getBindingResult(request.context(), parameter);
        
        if (Objects.isNull(bindingResult)) {
            throw new IllegalArgumentException("BindingResult 对象必须跟随在 @Validated 标识参数的下一个参数！");
        }
        
        return Future.succeededFuture(bindingResult);
    }
    
}
